package com.zbkj.crmeb.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.PageHelper;
import com.utils.DateUtil;
import com.zbkj.crmeb.express.model.Express;
import com.zbkj.crmeb.express.service.ExpressService;
import com.zbkj.crmeb.marketing.model.StoreCoupon;
import com.zbkj.crmeb.marketing.service.StoreCouponService;
import com.zbkj.crmeb.merchant.admin.service.MerStoreOrderService;
import com.zbkj.crmeb.store.dao.ChannelIntegralExchangeDao;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.request.ChannelIntegralExchangeRequest;
import com.zbkj.crmeb.store.request.OrderInfoDeliveryRequest;
import com.zbkj.crmeb.store.request.StoreOrderSendRequest;
import com.zbkj.crmeb.store.response.ChannelIntegralExchangeResponse;
import com.zbkj.crmeb.store.response.OutStoreOrderResponse;
import com.zbkj.crmeb.store.service.ChannelIntegralExchangeService;
import com.zbkj.crmeb.store.service.OrderInfoDeliveryService;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.user.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChannelIntegralExchangeServiceImpl extends ServiceImpl<ChannelIntegralExchangeDao, ChannelIntegralExchange> implements ChannelIntegralExchangeService {
    @Autowired
    private UserService userService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreCouponService storeCouponService;
    @Autowired
    private ExpressService expressService;
    @Autowired
    private OrderInfoDeliveryService orderInfoDeliveryService;
    @Autowired
    private MerStoreOrderService merStoreOrderService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;

    /**
     * 功能描述: 兑换记录
     * @Param: [request, merId, isApp]
     * @Return: java.util.List<com.zbkj.crmeb.store.response.ChannelIntegralExchangeResponse>
     * @Author: wangzh
     * @Date: 2023/3/7 11:27
     */
    @Override
    public List<ChannelIntegralExchangeResponse> getList(ChannelIntegralExchangeRequest request, Integer merId, Boolean isApp) {
        LambdaQueryWrapper<ChannelIntegralExchange> queryWrapper = new LambdaQueryWrapper<>();
        // 小程序请求接口时，返回用户兑换记录
        if (isApp) {
            Integer uid = userService.getUserIdException();
            queryWrapper.eq(ChannelIntegralExchange::getUid, uid);
        } else {
            queryWrapper.eq(ChannelIntegralExchange::getMerId, merId);
        }
        // 订单号删选不为空
        if (StringUtils.isNotBlank(request.getOrderId())) {
            queryWrapper.like(ChannelIntegralExchange::getOrderId, request.getOrderId());
        }
        // 用户名称删选不为空
        if (StringUtils.isNotBlank(request.getUserName())) {
            queryWrapper.like(ChannelIntegralExchange::getUserName, request.getUserName());
        }
        // 用户手机删选不为空
        if (StringUtils.isNotBlank(request.getUserPhone())) {
            queryWrapper.like(ChannelIntegralExchange::getUserPhone, request.getUserPhone());
        }
        // 订单状态筛选
        if (Objects.nonNull(request.getStatus())) {
            queryWrapper.eq(ChannelIntegralExchange::getStatus, request.getStatus());
        }
        queryWrapper.orderByDesc(ChannelIntegralExchange::getId);
        PageHelper.startPage(request.getPage(), request.getLimit());
        List<ChannelIntegralExchange> channelIntegralExchanges = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(channelIntegralExchanges)) {
            return new ArrayList<>();
        }
        // 商品与优惠券对应的集合
        Map<Integer, List<ChannelIntegralExchange>> map = channelIntegralExchanges.stream().collect(Collectors.groupingBy(ChannelIntegralExchange::getProductType));
        // 积分商品类型为商品时，查询商品信息
        Map<Integer, StoreProduct> storeProductMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(map.get(1))) {
            // 商品ids
            List<Integer> productIds = map.get(1).stream().map(ChannelIntegralExchange::getProductId).distinct().collect(Collectors.toList());
            List<StoreProduct> listInIds = storeProductService.getListInIds(productIds);
            storeProductMap = listInIds.stream().collect(Collectors.toMap(StoreProduct::getId, e -> e));
        }
        // 积分商品类型为优惠券时，查询优惠券信息
        Map<Integer, StoreCoupon> couponMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(map.get(2))) {
            List<Integer> couponIds = map.get(2).stream().map(ChannelIntegralExchange::getProductId).distinct().collect(Collectors.toList());
            List<StoreCoupon> storeCoupons = storeCouponService.listByIds(couponIds);
            couponMap = storeCoupons.stream().collect(Collectors.toMap(StoreCoupon::getId, e -> e));
        }
        // 规格名称
        Map<String, String> attrNameMap = new HashMap<>();
        // 规格id集合
        List<String> attrValueIds = channelIntegralExchanges.stream().map(ChannelIntegralExchange::getSourceSkuId).distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(attrValueIds)) {
            List<StoreProductAttrValue> storeProductAttrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                    .in(StoreProductAttrValue::getSourceSkuId, attrValueIds));
            attrNameMap = storeProductAttrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getSourceSkuId, StoreProductAttrValue::getSuk));
        }
        List<ChannelIntegralExchangeResponse> responses = new ArrayList<>();
        for (ChannelIntegralExchange channelIntegralExchange : channelIntegralExchanges) {
            ChannelIntegralExchangeResponse response = new ChannelIntegralExchangeResponse();
            BeanUtils.copyProperties(channelIntegralExchange, response);
            switch (channelIntegralExchange.getProductType()){
                case 1:
                    response.setProduct(storeProductMap.get(channelIntegralExchange.getProductId()));
                    if (channelIntegralExchange.getStatus() == 1) {
                        response.setStatus("待发货");
                    } else {
                        response.setStatus("已发货");
                    }
                    response.setSku(attrNameMap.get(channelIntegralExchange.getSourceSkuId()));
                    break;
                case 2:
                    response.setProduct(couponMap.get(channelIntegralExchange.getProductId()));
                    response.setStatus("已发放");
                    break;
            }
            response.setExchangeTime(DateUtil.dateToStr(channelIntegralExchange.getCreateTime(), Constants.DATE_FORMAT));
            responses.add(response);
        }
        return responses;
    }

    /**
     * 功能描述: 兑换商品发货
     * @Param: [request]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2023/3/8 14:18
     */
    @Override
    public Boolean sendProduct(StoreOrderSendRequest request) {
        ChannelIntegralExchange channelIntegralExchange = this.getById(request.getId());
        try {
            if (!channelIntegralExchange.getStatus().equals(1)) {
                throw new CrmebException("当前订单状态无法发货");
            }
            Express express;
            if (request.getName().equals("同城配送")) {
                express = new Express();
            } else {
                express = expressService.info(Integer.parseInt(request.getExpressId()));
            }
            channelIntegralExchange.setStatus(2);
            this.updateById(channelIntegralExchange);
            OrderInfoDeliveryRequest delivery = new OrderInfoDeliveryRequest();
            delivery.setOrderInfoId(request.getId());
            delivery.setDeliveryCompany(express.getName());
            delivery.setDeliveryNumber(request.getExpressCode());
            delivery.setName(request.getName());
            delivery.setDeliveryCode(express.getCode());
            delivery.setPhone(request.getPhone());
            delivery.setExpressId(StringUtils.isBlank(request.getExpressId()) ? null : Integer.parseInt(request.getExpressId()));
            delivery.setLogisticsStage(request.getLogisticsStage());
            if (!Objects.isNull(request.getLevel())) {
                delivery.setLevel(request.getLevel());
            }
            delivery.setChannel(request.getChannel());
            delivery.setIsExchange(true);
            orderInfoDeliveryService.addDelivery(delivery);
            List<OrderInfoDelivery> deliveryList = orderInfoDeliveryService.list(Wrappers.<OrderInfoDelivery>lambdaQuery()
                    .eq(OrderInfoDelivery::getOrderInfoId, channelIntegralExchange.getId()));
            OutStoreOrderResponse outStoreOrderResponse = new OutStoreOrderResponse();
            outStoreOrderResponse.setOrderId(channelIntegralExchange.getOrderId());
            outStoreOrderResponse.setOrderInfoDeliverys(deliveryList);

            if (27 == channelIntegralExchange.getMerId()) {
                merStoreOrderService.deliverGoods(channelIntegralExchange.getOrderId().split("DH")[1], express.getCode(), request.getExpressCode());
            } else {
                merStoreOrderService.sendBackOrder(channelIntegralExchange.getMerId(), outStoreOrderResponse, null);
            }
        } catch (Exception e) {
            throw new CrmebException("快递发货失败！" + e.getMessage());
        }
        return true;
    }

    /**
     * 功能描述: 获取兑换商品物流记录
     * @Param: [request]
     * @Return: java.util.List<com.zbkj.crmeb.store.model.OrderInfoDelivery>
     * @Author: wangzh
     * @Date: 2023/3/8 14:38
     */
    @Override
    public List<OrderInfoDelivery> getDeliveryList(OrderInfoDeliveryRequest request) {
        return orderInfoDeliveryService.getDeliveryList(request);
    }
}
